/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Common.CommonUtil;
import Common.Global;
import DAO.TrackedProductDAO;
import hibernate.entity.Account;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author NamDH
 */
public class HomeController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("btAction");
            if (action.equals("AddProduct")) {

                String url = request.getParameter("url");
                HttpSession session = request.getSession(false);

                if (CommonUtil.checkProductURL(url)) {

                    String webcontent = CommonUtil.getWebContentbyURL(url);
                    String productName = "";
                    double productPrice = 0;
                    String productImage = "";

                    productName = CommonUtil.getTagContent(webcontent, Common.Global.ebay_ProductName_KeySearch);
                    productPrice = CommonUtil.getNumberfromString(CommonUtil.getTagContent(webcontent, Common.Global.ebay_ProductPrice_KeySearch));
                    productImage = CommonUtil.getImagesrc(webcontent, Common.Global.ebay_ProductImage_KeySearch);

                    if (!productName.equals("")) {
                        session.setAttribute("URL", url);
                        session.setAttribute("PNAME", productName);
                        session.setAttribute("PNAME2", productName);
                        session.setAttribute("PPRICE", productPrice);
                        session.setAttribute("PIMAGE", productImage);
                    } else {
                        session.setAttribute("INVALIDURL", "Invalid url!");
                    }
                    //                session.setAttribute("COLLECTIONS", collections);
                } else {
                    session.setAttribute("INVALIDURL", "Invalid url!");
                }
                response.sendRedirect(Global.homepage);
            } else if (action.equals("track")) {
                double desiredPrice = 0;
                HttpSession session = request.getSession(false);


                Account account = (Account) session.getAttribute("ACCOUNT");
                if (account != null) {
                    String dPrice = request.getParameter("desired_price");
                    if (!dPrice.equals("")) {
                        desiredPrice = Double.parseDouble(dPrice);
                    }

                    String url = session.getAttribute("URL").toString();
                    String productName = session.getAttribute("PNAME").toString();
                    double productPrice = Double.parseDouble(session.getAttribute("PPRICE").toString());
                    String productImage = session.getAttribute("PIMAGE").toString();

                    //clear session
                    session.removeAttribute("URL");
                    session.removeAttribute("PNAME");
                    session.removeAttribute("PPRICE");
                    session.removeAttribute("PIMAGE");
                    TrackedProductDAO trackedProductDAO = new TrackedProductDAO();
                    trackedProductDAO.addNewTrackedProduct(account.getAccountID(), url, productName, productPrice, productImage, desiredPrice);
                    response.sendRedirect(Global.showproduct);
                } else {
                    response.sendRedirect(Global.loginpage);
                }

            } else if (action.equals("ExTrack")) {
                HttpSession session = request.getSession();
                String isCallBack = "";
                try {
                    isCallBack = session.getAttribute("URL").toString();
                } catch (Exception ex) {
                }

                Account account = (Account) session.getAttribute("ACCOUNT");
                if (isCallBack.equals("")) {
                    double desireprice = Double.parseDouble(request.getParameter("desired_price"));
                    String PURL = request.getParameter("PURL");
                    String PName = request.getParameter("PName");
                    double PPrice = CommonUtil.getNumberfromString(request.getParameter("PPrice"));
                    String PImage = request.getParameter("PImage");
                    if (account == null) {
                        session.setAttribute("URL", PURL);
                        session.setAttribute("PNAME", PName);
                        session.setAttribute("PPRICE", PPrice);
                        session.setAttribute("PIMAGE", PImage);
                        session.setAttribute("DPRICE", desireprice);
                        response.sendRedirect(Global.Exloginpage);
                        return;
                    }
                    TrackedProductDAO trackedProductDAO = new TrackedProductDAO();
                    trackedProductDAO.addNewTrackedProduct(account.getAccountID(), PURL, PName, PPrice, PImage, desireprice);
                    response.sendRedirect("ExSuccess.html");

                } else {
                    double desireprice = Double.parseDouble(session.getAttribute("DPRICE").toString());
                    String url = session.getAttribute("URL").toString();
                    String productName = session.getAttribute("PNAME").toString();
                    double productPrice = Double.parseDouble(session.getAttribute("PPRICE").toString());
                    String productImage = session.getAttribute("PIMAGE").toString();

                    TrackedProductDAO trackedProductDAO = new TrackedProductDAO();
                    trackedProductDAO.addNewTrackedProduct(account.getAccountID(), url, productName, productPrice, productImage, desireprice);
                    response.sendRedirect("ExSuccess.html");

                    session.removeAttribute("URL");
                    session.removeAttribute("PNAME");
                    session.removeAttribute("PPRICE");
                    session.removeAttribute("PIMAGE");
                    session.removeAttribute("DPRICE");
                }

            }
            if (action.equals("logout")) {
                HttpSession session = request.getSession(false);
                if (session != null) {
                    session.invalidate();
                }
                response.sendRedirect(Global.homepage);
            } else if (action.equals("LoadSearchUser")) {
                HttpSession session = request.getSession(true);
                session.removeAttribute("LOADSEARCHPRODUCT");
                session.setAttribute("LOADSEARCHUSER", out);
                RequestDispatcher rd = request.getRequestDispatcher("productdetail.jsp");
                rd.forward(request, response);
            } else if (action.equals("LoadSearchProduct")) {
                HttpSession session = request.getSession(true);
                session.removeAttribute("LOADSEARCHUSER");
                session.setAttribute("LOADSEARCHPRODUCT", out);
                RequestDispatcher rd = request.getRequestDispatcher("ManageProductController?btAction=LoadTrackedProduct");
                rd.forward(request, response);
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
